package cn.china.myspringboot.controller;

import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@MultipartConfig
@CrossOrigin
public class UploadController {

    @RequestMapping("/upload")
    public String upload(MultipartFile multipartFile,HttpServletResponse resp,String name,Integer age) throws IOException {

    resp.setHeader("Access-Control-Allow-Origin","*");
        System.out.println(name+","+age);

        String path= ResourceUtils.getURL("classpath:").getPath();
        System.out.println(path);
        //输入流
        BufferedInputStream bis=new BufferedInputStream(multipartFile.getInputStream());
        File file=new File(path,"static/images/");
        if(!file.exists()){
            file.mkdirs();
        }
        String fileName=System.currentTimeMillis()+multipartFile.getOriginalFilename();
        String realPath=file.getAbsolutePath()+"/"+fileName;
        //输出流
        BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(realPath));
        byte[] bytes=new byte[1024];
        int d=-1;
        while((d=bis.read(bytes))!=-1){
            bos.write(bytes);
            bos.flush();
        }
        bis.close();
        bos.close();

        String imageUrl="http://localhost:8082/images/"+fileName;
        System.out.println(imageUrl);

        return null;
    }

    @RequestMapping("/path")
    public String test() throws IOException {

        File file=new File("src/main/resources/static/images");
        for(File f:file.listFiles()){
            System.out.println(f.getName());
        }
        return null;

    }
}
